package times

import (
	"fmt"
	"strings"
)

type Cron struct {
	second string
	minute string
	hour   string
	dom    string // day of month
	month  string
	dow    string // day of week
}

func NewCron(args ...string) *Cron {
	cron := new(Cron)
	index := 0

	if len(args) > index {
		cron.second = args[index]
		index++
	}

	if len(args) > index {
		cron.minute = args[index]
		index++
	}

	if len(args) > index {
		cron.hour = args[index]
		index++
	}

	if len(args) > index {
		cron.dom = args[index]
		index++
	}

	if len(args) > index {
		cron.month = args[index]
		index++
	}

	if len(args) > index {
		cron.dow = args[index]
	}

	return cron
}

func (c *Cron) String() string {
	builder := new(strings.Builder)

	build(builder, c.second)
	build(builder, c.minute)
	build(builder, c.hour)
	build(builder, c.dom)
	build(builder, c.month)
	build(builder, c.dow)

	return builder.String()
}

func build(builder *strings.Builder, elem string) {
	if elem != "" {
		fmt.Fprintf(builder, elem)
	} else {
		fmt.Fprintf(builder, "*")
	}

	fmt.Fprintf(builder, " ")
}
